package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.constants.NewsConstant;
import com.usian.model.article.ApAuthor;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.mapper.UserFansMapper;
import com.usian.user.mapper.UserFollowMapper;
import com.usian.user.service.UserFollowService;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserFollowServiceImpl extends BaseServiceImpl<UserFollowMapper, ApUserFollow> implements UserFollowService {
    @Autowired
    private ApUserMapper userMapper;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private UserFansMapper fansMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 关注和取消关注的接口
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult followOrCancel(UserRelationDto dto) {
        if (dto == null || dto.getOperation() == null || dto.getAuthorId() == null || (dto.getOperation() != 0 && dto.getOperation() != 1)||dto.getArticleId() == null)
            return paramError;
        Integer userId = ThreadLocalUtils.getUserId();
        if (userId == null)return needLogin;
        ApUser user = userMapper.selectById(userId);
        if (user == null)return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        //根据作者的id查询作者信息
        ApAuthor author = articleFeign.getById(dto.getAuthorId());

        LambdaQueryWrapper<ApUserFollow> followWrapper = Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId).eq(ApUserFollow::getFollowId, author.getUserId());
        LambdaQueryWrapper<ApUserFan> fansWrapper = Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, author.getUserId()).eq(ApUserFan::getFansId, userId);
        if (dto.getOperation() == 0){//关注
            //在关注表插入关注数据
            int count = count(followWrapper);
            if (count == 0){
                ApUserFollow follow = new ApUserFollow();
                follow.setUserId(userId);
                follow.setFollowId(author.getUserId());
                follow.setFollowName(author.getName());
                follow.setLevel((short) 2);
                follow.setIsNotice(true);
                follow.setCreatedTime(new Date());
                save(follow);
            }
            //在粉丝表插入粉丝数据
            Integer fansCount = fansMapper.selectCount(fansWrapper);
            if (fansCount == 0){
                ApUserFan fan = new ApUserFan();
                fan.setUserId(author.getUserId());
                fan.setFansId(userId.longValue());
                fan.setFansName(user.getName());
                fan.setLevel((short) 4);
                fan.setCreatedTime(new Date());
                fan.setIsDisplay(true);
                fan.setIsShieldLetter(true);
                fan.setIsShieldComment(true);
                fansMapper.insert(fan);
            }
            Map<String,Object> messageMap = new HashMap<>();
            messageMap.put("userId",userId);
            messageMap.put("followId",author.getUserId());
            messageMap.put("articleId",dto.getArticleId());
            kafkaTemplate.send(NewsConstant.USER_FOLLOW_BEHAVIOR, JSON.toJSONString(messageMap));
        } else {
            remove(followWrapper);
            fansMapper.delete(fansWrapper);
        }
        return success;
    }
}
